<template>
  <div class="order-manage">
    <!-- 页面标题 -->
    <h3>订单管理</h3>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never" style="width: 100%;">
      <el-form :model="query" label-width="80px">
        <!-- 下单时间筛选 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单时间">
              <div class="date-range-wrapper">
                <el-date-picker
                  v-model="query.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 180px;"
                />
                <span class="divider">至</span>
                <el-date-picker
                  v-model="query.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 180px;"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 订单搜索 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单搜索">
              <div class="search-wrapper">
                <el-select v-model="searchType" placeholder="筛选类型" style="width: 120px;">
                  <el-option label="订单号" value="orderNo" />
                </el-select>
                <el-input
                  v-model="searchValue"
                  placeholder="请输入订单号"
                  style="width: 200px; margin: 0 10px;"
                />
                <el-button type="primary" size="small" @click="handleFilter">筛选</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 状态标签栏 -->
    <el-card class="status-card" shadow="never" style="width: 100%;">
      <el-tag
        v-for="(item, index) in statusTags"
        :key="index"
        :type="item.type"
        @click="handleStatusFilter(item.value)"
        class="mr-2 cursor-pointer"
        size="small"
      >
        {{ item.label }}
      </el-tag>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="list-card" shadow="never" style="width: 100%;">
      <el-table 
        :data="orderList" 
        border 
        style="width: 100%" 
        fit 
      >
        <el-table-column prop="createTime" label="设备信息" width="400">
          <template #default="{ row }">
            <div>下单时间：{{ row.createTime }}</div>
            <div>
              <span :class="['status-badge', getStatusClass(row.orderStatus)]">
                {{ getStatusText(row.orderStatus) }}
              </span>
              <span style="margin-left: 10px;">订单号：{{ row.orderId }}</span><br/>
              <span style="margin-left: 10px;">设备名称：{{ row.equipment.brand }} - {{ row.equipment.model }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="金额" width="160">
          <template #default="{ row }">
            <div>总金额：<strong>{{ row.orderAmount }}元</strong></div>
            <div><a href="javascript:;" @click="handleEditPrice(row)">修改价格</a></div>
          </template>
        </el-table-column>

        <el-table-column label="实际付款" width="100">
          <template #default="{ row }">
            {{ row.depositAmount + row.balanceAmount == 0 ? 0 : row.depositAmount + row.balanceAmount }}元
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleOperation(row)">操作</el-button>
            <el-button type="info" size="small" @click="handleViewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pageNum"
        :page-sizes="[5, 10, 20]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px;"
      />
    </el-card>
  </div>
  <!-- 分配业务员模态框 -->
    <el-dialog
      v-model="allocateDialogVisible"
      title="分配业务员"
      width="500px"
      :before-close="closeAllocateDialog"
      destroy-on-close
    >
      <!-- 搜索区域 -->
      <div class="allocate-search">
        <el-input
          v-model="businessmanQuery.keyword"
          placeholder="输入用户名或姓名搜索"
          class="search-input"
          @keyup.enter="getBusinessmanList"
        >
          <template #append>
            <el-button type="primary" @click="getBusinessmanList">查找</el-button>
          </template>
        </el-input>
      </div>

      <!-- 业务员列表 -->
      <el-table
        :data="businessmanList"
        border
        v-loading="businessmanLoading"
        element-loading-text="加载中..."
        class="businessman-table"
      >
        <el-table-column label="姓名" prop="name" width="350"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="confirmAllocate(scope.row)"
            >
              选择分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="businessman-pagination">
        <el-pagination
          v-model:current-page="businessmanPagination.currentPage"
          v-model:page-size="businessmanPagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="businessmanPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBusinessmanSizeChange"
          @current-change="handleBusinessmanCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="closeAllocateDialog">取消</el-button>
      </template>
    </el-dialog>
    <!-- 查看详情模态框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :before-close="closeDetailDialog"
      destroy-on-close
    >

      <!-- 新增：图片显示区域 -->
      <div class="image-preview-container">
        <div class="image-label">设备图片：</div>
        <el-image
          v-if="currentOrder2.equipmentImages && currentOrder2.equipmentImages.length > 0"
          :src="currentOrder2.equipmentImages[0].imageUrl"
          fit="contain"
          class="equipment-image"
          fallback-src="https://picsum.photos/400/300"
          preview-teleported
        >
          <template #error>
            <div class="image-error">图片加载失败</div>
          </template>
        </el-image>
        <div v-else class="empty-image">
          <span>暂无设备图片</span>
        </div>
      </div>

      <div class="detail-container">
        <!-- 订单基本信息 -->
        <div class="detail-item">
          <div class="label">订单号：</div>
          <div class="value">{{ currentOrder2.orderId }}</div>
        </div>
        
        <div class="detail-item">
          <div class="label">下单时间：</div>
          <div class="value">{{ currentOrder2.createTime }}</div>
        </div>
        
        <div class="detail-item">
          <div class="label">设备标题：</div>
          <div class="value">{{ currentOrder2.equipment.brand }} - {{ currentOrder2.equipment.model }}</div>
        </div>
        
        <div class="detail-item">
          <div class="label">设备车源号：</div>
          <div class="value">{{ currentOrder2.equipment.equipmentId }}</div>
        </div>
        
        <div class="detail-item">
          <div class="label">订单状态：</div>
          <div class="value">
            <span :class="['status-badge', getStatusClass(currentOrder2.orderStatus)]">
              {{ getStatusText(currentOrder2.orderStatus) }}
            </span>
          </div>
        </div>
        
        <div class="detail-item">
          <div class="label">总金额：</div>
          <div class="value">{{ currentOrder2.orderAmount }}元</div>
        </div>
        
        <div class="detail-item">
          <div class="label">定金：</div>
          <div class="value">{{ currentOrder2.depositAmount }}元</div>
        </div>
        
        <div class="detail-item">
          <div class="label">尾款：</div>
          <div class="value">{{ currentOrder2.balanceAmount }}元</div>
        </div>
        
        <div class="detail-item">
          <div class="label">实际付款：</div>
          <div class="value">{{ currentOrder2.depositAmount + currentOrder2.balanceAmount }}元</div>
        </div>
        
        <div class="detail-item">
          <div class="label">支付方式：</div>
          <div class="value">线上支付</div>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeDetailDialog">关闭</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import httpInstance from '@/utils/http';


// 查询参数：orderStatus明确为null，初始化显示全部状态
const query = reactive({
  startTime: null,
  endTime: null,
  orderNo: null,
  pageNum: 1,
  pageSize: 5,
  orderStatus: null, 
});

// 搜索类型与值
const searchType = ref('orderNo');
const searchValue = ref('');

// 订单列表数据
const orderList = ref([]);
const total = ref(0);

// 分配业务员相关数据
const allocateDialogVisible = ref(false);
const currentAllocateEquipment = ref(null);
const businessmanList = ref([]);
const businessmanLoading = ref(false);
const businessmanQuery = reactive({
  keyword: ''
});
const businessmanPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

const detailDialogVisible = ref(false);
const currentOrder2 = ref(null);

// 查看详情功能
const handleViewDetails = (row) => {
  console.log('查看详情', row);
  currentOrder2.value = row;
  detailDialogVisible.value = true;
};

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false;
};

// 状态标签
const statusTags = [
  { label: '全部', value: null, type: null },
  { label: '待支付定金', value: 0, type: 'info' },
  { label: '已支付定金', value: 1, type: 'success' },
  { label: '待支付尾数', value: 2, type: 'warning' },
  { label: '已支付尾数', value: 3, type: 'success' },
  { label: '已发货', value: 4, type: 'success' },
  { label: '已收货', value: 5, type: 'success' },
  { label: '已完成', value: 6, type: 'success' },
  { label: '已取消', value: 7, type: 'danger' },
];

// 初始化页面
onMounted(() => {
  fetchOrderList();
});

// 获取订单列表时更新
const fetchOrderList = () => {
  console.log('查询参数', query);
  httpInstance.get('/eduservice/order/getOrderList', { params: query })
    .then(res => {
      if (res.data.success) {
        const pageInfo = res.data.data.list;
        orderList.value = pageInfo.list;
        total.value = pageInfo.total;
      } else {
        ElMessage.error('获取订单列表失败');
      }
    })
    .catch(err => {
      console.error(err);
      ElMessage.error('网络异常，请稍后重试');
    });
};

// 获取业务员列表数据分页
const getBusinessmanList = async () => {
  businessmanLoading.value = true;
  try {
    const businessmanVo = {
      username: businessmanQuery.keyword,
      name: businessmanQuery.keyword 
    };
    
    const response = await httpInstance.post(
      `/eduservice/businessman/getBusinessmanPage/${businessmanPagination.currentPage}/${businessmanPagination.pageSize}`,
      businessmanVo
    );

    businessmanList.value = response.data.list || [];
    businessmanPagination.total = response.data.total || 0;

  } catch (error) {
    ElMessage.error('获取业务员列表失败');
    console.error('业务员列表请求错误:', error);
  } finally {
    businessmanLoading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待支付定金';
    case 1: return '已支付定金';
    case 2: return '待支付尾数';
    case 3: return '已支付尾数';
    case 4: return '已发货';
    case 5: return '已收货';
    case 6: return '已完成';
    case 7: return '已取消';
  }
};

// 状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'status-unpaid';     
    case 1: return 'status-paid';       
    case 2: return 'status-pending';    
    case 3: return 'status-tail-paid';  
    case 4: return 'status-shipped';    
    case 5: return 'status-received';   
    case 6: return 'status-completed';  
    case 7: return 'status-cancelled';  
  }
};

// 筛选操作
const handleFilter = () => {
  if (searchType.value === 'orderNo') {
    query.orderNo = searchValue.value;
  }
  query.pageNum = 1;
  fetchOrderList();
};

// 状态标签筛选
const handleStatusFilter = (value) => {
  query.orderStatus = value;
  fetchOrderList();
};

// 分页-每页条数变更
const handleSizeChange = (val) => {
  query.pageSize = val;
  query.pageNum = 1; // 重置当前页为第一页
  fetchOrderList();
};

// 分页-当前页变更
const handleCurrentChange = (val) => {
  query.pageNum = val;
  fetchOrderList();
};

// 业务员分页大小变化
const handleBusinessmanSizeChange = (size) => {
  businessmanPagination.pageSize = size;
  getBusinessmanList();
};

// 业务员当前页变化
const handleBusinessmanCurrentChange = (page) => {
  businessmanPagination.currentPage = page;
  getBusinessmanList();
};

// 修改价格功能
const handleEditPrice = (row) => {
  ElMessage.info('修改价格功能待实现');
};
// 检查设备是否已分配业务员
const checkEquipmentAssigned = async (equipmentId) => {
  try {
    const response = await httpInstance.get(`/eduservice/businessmanEquipment/getBusinessmanById/${equipmentId}`);
    if (response.data && response.data.businessmanId) {
      return {
        assigned: true,
        businessman: response.data
      };
    } else {
      return {
        assigned: false,
        businessman: null
      };
    }
  } catch (error) {
    console.error('检查设备分配状态失败:', error);
    return {
      assigned: false,
      businessman: null
    };
  }
};

const currentOrder = ref(null);
// 操作按钮处理
const handleOperation = async (row) => {
  currentOrder.value = row;

  switch (row.orderStatus) {
    case 0:
      ElMessage.warning('买家还未支付定金');
      break;
    case 1:
    case 2:
      console.log(row.equipmentId)
      const assignResult = await checkEquipmentAssigned(row.equipmentId);
      if (assignResult.assigned) {
        ElMessage.info(`设备已分配给业务员: ${assignResult.businessman.businessman.name}`);
      } else {
        currentAllocateEquipment.value = row;
        businessmanQuery.keyword = '';
        businessmanPagination.currentPage = 1;
        getBusinessmanList();
        allocateDialogVisible.value = true;
      }
      break;
    case 3:
      // 先检查是否分配业务员，再确认发货
      const assignResult2 = await checkEquipmentAssigned(row.equipmentId);
      if (!assignResult2.assigned) {
        ElMessage.warning('请先分配业务员后再发货');
        // 弹出分配业务员对话框
        currentAllocateEquipment.value = row;
        businessmanQuery.keyword = '';
        businessmanPagination.currentPage = 1;
        getBusinessmanList();
        allocateDialogVisible.value = true;
        break;
      }
      ElMessageBox.confirm('确认发货吗？', '确认发货', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        httpInstance.put('/eduservice/order/updateOrder', {
          orderNo: row.orderId,
          orderStatus: 4 
        });
        ElMessage.success('已确认发货');
        fetchOrderList();
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
      break;
    case 4:
      ElMessage.info('已发货，无需其他操作');
      break;
    default:
      ElMessage.info('当前状态不支持操作');
  }
};

// 确认分配业务员
const confirmAllocate = async (businessman) => {
  try {
    ElMessageBox.confirm(`确定将设备【${currentAllocateEquipment.value.equipmentId}】分配给业务员【${businessman.name}】吗？`, '确认分配', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      httpInstance.post(`/eduservice/businessmanEquipment/allocate/${currentAllocateEquipment.value.equipmentId}`, {
        businessmanId: businessman.businessmanId
      });
      ElMessage.success('分配成功');
    }).catch(() => {
      ElMessage.error('取消分配');
    });
    allocateDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('分配失败，请重试');
    console.error('分配错误:', error);
  }
};

// 关闭分配弹窗
const closeAllocateDialog = () => {
  allocateDialogVisible.value = false;
};
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.filter-card,
.status-card,
.list-card {
  margin-bottom: 20px;
}

.cursor-pointer {
  cursor: pointer;
}

.date-range-wrapper {
  display: flex;
  align-items: center;
}

.divider {
  margin: 0 10px;
  color: #909399;
}

.search-wrapper {
  display: flex;
  align-items: center;
}

.el-table .cell {
  white-space: normal;
  word-break: break-all;
}

.el-table .cell .el-button {
  margin: 2px 0;
  display: block;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  text-align: right;
}

.status-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status-unpaid {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.status-paid {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.status-pending {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.status-tail-paid {
  background-color: #ecf5ff;
  color: #409eff;
  border: 1px solid #b3d8ff;
}

.status-shipped {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.status-received {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.status-cancelled {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

.status-unknown {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #d3d4d6;
}

/* 在 style scoped 中添加以下样式 */
.detail-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 6px;
  margin: 20px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}

.label {
  width: 100px;
  font-weight: 500;
  color: #666;
}

.value {
  flex: 1;
  color: #333;
}

.status-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

/* 新增：图片预览样式 */
.image-preview-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 6px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  flex-direction: column;
}
.image-label {
  align-self: flex-start;
  font-weight: 500;
  color: #666;
  margin-bottom: 10px;
}

.equipment-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
}

.empty-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #f56c6c;
  background-color: #fff;
}

/* 优化图片预览弹窗样式 */
:deep(.el-image-viewer__wrapper) {
  z-index: 2000 !important;
}
</style>